<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('close')"
    title="数据备份"
    width="600px"
    :close-on-click-modal="false"
  >
    <div class="backup-container">
      <!-- 备份选项 -->
      <div class="backup-options">
        <h4>备份选项</h4>
        <div class="options-grid">
          <el-card class="option-card" :class="{ active: backupType === 'full' }">
            <div class="option-content" @click="backupType = 'full'">
              <el-radio v-model="backupType" label="full">
                <div class="option-info">
                  <div class="option-title">完整备份</div>
                  <div class="option-desc">备份所有账号数据，包括密码</div>
                </div>
              </el-radio>
            </div>
          </el-card>
          
          <el-card class="option-card" :class="{ active: backupType === 'partial' }">
            <div class="option-content" @click="backupType = 'partial'">
              <el-radio v-model="backupType" label="partial">
                <div class="option-info">
                  <div class="option-title">部分备份</div>
                  <div class="option-desc">仅备份账号信息，不包含密码</div>
                </div>
              </el-radio>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 备份格式 -->
      <div class="format-options">
        <h4>导出格式</h4>
        <div class="format-grid">
          <el-card 
            v-for="format in exportFormats" 
            :key="format.value"
            class="format-card"
            :class="{ active: exportFormat === format.value }"
            @click="exportFormat = format.value"
          >
            <div class="format-info">
              <div class="format-icon">{{ format.icon }}</div>
              <div class="format-details">
                <div class="format-name">{{ format.name }}</div>
                <div class="format-desc">{{ format.description }}</div>
                <div class="format-features">
                  <span v-for="feature in format.features" :key="feature" class="feature-tag">
                    {{ feature }}
                  </span>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 安全选项 -->
      <div class="security-options" v-if="backupType === 'full'">
        <h4>安全选项</h4>
        <div class="security-controls">
          <el-checkbox v-model="encryptBackup">
            <span>加密备份文件</span>
            <el-tooltip content="使用密码保护备份文件，提高安全性">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-checkbox>
          
          <div v-if="encryptBackup" class="encryption-password">
            <el-input
              v-model="encryptionPassword"
              type="password"
              placeholder="设置备份文件密码"
              show-password
              :rules="passwordRules"
            />
            <div class="password-strength" v-if="encryptionPassword">
              <div class="strength-bar">
                <div 
                  class="strength-fill" 
                  :class="passwordStrengthClass"
                  :style="{ width: passwordStrengthWidth }"
                ></div>
              </div>
              <span class="strength-text">{{ passwordStrengthText }}</span>
            </div>
            <div v-if="encryptBackup && encryptionPassword && passwordStrength < 2" class="password-warning">
              <el-alert
                title="密码强度不足"
                description="为确保备份安全，请使用包含大小写字母、数字的密码（至少8位）"
                type="warning"
                :closable="false"
                show-icon
                size="small"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 备份预览 -->
      <div class="backup-preview">
        <h4>备份预览</h4>
        <div class="preview-stats">
          <div class="stat-item">
            <span class="stat-label">账号总数：</span>
            <span class="stat-value">{{ accountsStore.accounts.length }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">预计文件大小：</span>
            <span class="stat-value">{{ estimatedSize }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">备份时间：</span>
            <span class="stat-value">{{ new Date().toLocaleString() }}</span>
          </div>
        </div>
      </div>

      <!-- 备份历史 -->
      <div class="backup-history">
        <h4>备份历史</h4>
        <div v-if="backupHistory.length === 0" class="no-history">
          暂无备份历史
        </div>
        <div v-else class="history-list">
          <div
            v-for="(backup, index) in backupHistory"
            :key="index"
            class="history-item"
          >
            <div class="history-info">
              <div class="history-name">{{ backup.name }}</div>
              <div class="history-details">
                {{ backup.date }} | {{ backup.type }} | {{ backup.format }}
              </div>
            </div>
            <div class="history-actions">
              <el-button size="small" type="text" @click="downloadBackup(backup)">
                下载
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('close')">取消</el-button>
        <el-button 
          type="primary" 
          @click="performBackup"
          :disabled="!canBackup"
          :loading="isBackingUp"
        >
          {{ isBackingUp ? '备份中...' : '开始备份' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useAccountsStore } from '../stores/accounts'
import { ElMessage, ElAlert } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
import CryptoJS from 'crypto-js'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close'])

const accountsStore = useAccountsStore()
const backupType = ref('full')
const exportFormat = ref('json')
const encryptBackup = ref(false)
const encryptionPassword = ref('')
const isBackingUp = ref(false)
const backupHistory = ref([])

// 导出格式配置
const exportFormats = [
  {
    value: 'json',
    name: 'JSON',
    icon: '📋',
    description: '结构化数据格式，便于程序处理',
    features: ['可读性好', '支持嵌套', '程序友好']
  },
  {
    value: 'csv',
    name: 'CSV',
    icon: '📊',
    description: 'Excel表格格式，便于数据分析',
    features: ['Excel兼容', '数据分析', '通用格式']
  },
  {
    value: 'txt',
    name: 'TXT',
    icon: '📝',
    description: '纯文本格式，任何设备可读',
    features: ['通用兼容', '纯文本', '体积小']
  },
  {
    value: 'xml',
    name: 'XML',
    icon: '🗂️',
    description: '标准标记语言，企业级标准',
    features: ['标准格式', '可验证', '企业级']
  },
  {
    value: 'html',
    name: 'HTML',
    icon: '🌐',
    description: '网页格式，浏览器直接查看',
    features: ['可视化', '浏览器', '打印友好']
  },
  {
    value: 'yaml',
    name: 'YAML',
    icon: '⚙️',
    description: '配置文件格式，人类可读',
    features: ['配置友好', '可读性强', '简洁语法']
  }
]

// 密码强度检查
const passwordStrength = computed(() => {
  if (!encryptionPassword.value) return 0
  
  let score = 0
  if (encryptionPassword.value.length >= 8) score += 1
  if (/[a-z]/.test(encryptionPassword.value)) score += 1
  if (/[A-Z]/.test(encryptionPassword.value)) score += 1
  if (/[0-9]/.test(encryptionPassword.value)) score += 1
  if (/[^A-Za-z0-9]/.test(encryptionPassword.value)) score += 1
  
  return score
})

const passwordStrengthClass = computed(() => {
  if (passwordStrength.value <= 2) return 'weak'
  if (passwordStrength.value <= 3) return 'medium'
  return 'strong'
})

const passwordStrengthWidth = computed(() => {
  return (passwordStrength.value / 5) * 100 + '%'
})

const passwordStrengthText = computed(() => {
  if (passwordStrength.value <= 2) return '弱'
  if (passwordStrength.value <= 3) return '中等'
  return '强'
})

// 估算文件大小
const estimatedSize = computed(() => {
  const accounts = accountsStore.accounts
  let sizeInBytes = 0
  
  const baseData = backupType.value === 'full' ? accounts : accounts.map(acc => ({
    name: acc.name,
    username: acc.username,
    url: acc.url,
    category: acc.category,
    notes: acc.notes
  }))
  
  switch (exportFormat.value) {
    case 'json':
      sizeInBytes = JSON.stringify(baseData).length
      break
    case 'csv':
      sizeInBytes = accounts.length * 120 // 平均每条记录120字节
      break
    case 'txt':
      sizeInBytes = accounts.length * 100 // 平均每条记录100字节
      break
    case 'xml':
      sizeInBytes = accounts.length * 200 // XML标签较多
      break
    case 'html':
      sizeInBytes = accounts.length * 180 + 2000 // HTML结构 + 头部
      break
    case 'yaml':
      sizeInBytes = accounts.length * 90 // YAML较简洁
      break
    default:
      sizeInBytes = JSON.stringify(baseData).length
  }
  
  if (sizeInBytes < 1024) return sizeInBytes + ' B'
  if (sizeInBytes < 1024 * 1024) return Math.round(sizeInBytes / 1024) + ' KB'
  return Math.round(sizeInBytes / (1024 * 1024)) + ' MB'
})

// 检查是否可以备份
const canBackup = computed(() => {
  if (accountsStore.accounts.length === 0) return false
  if (encryptBackup.value && !encryptionPassword.value) return false
  if (encryptBackup.value && passwordStrength.value < 2) return false // 降低要求到至少2分
  return true
})

// 生成备份数据
const generateBackupData = () => {
  const accounts = accountsStore.accounts
  const timestamp = new Date().toISOString()
  
  const baseData = {
    backupInfo: {
      date: timestamp,
      type: backupType.value,
      format: exportFormat.value,
      version: '1.0.0',
      totalAccounts: accounts.length
    }
  }
  
  if (backupType.value === 'full') {
    baseData.accounts = accounts
  } else {
    baseData.accounts = accounts.map(account => ({
      id: account.id,
      name: account.name,
      username: account.username,
      url: account.url,
      category: account.category,
      notes: account.notes,
      isFavorite: account.isFavorite,
      createdAt: account.createdAt,
      updatedAt: account.updatedAt
    }))
  }
  
  return baseData
}

// 转换为不同格式
const convertToFormat = (data) => {
  switch (exportFormat.value) {
    case 'json':
      return JSON.stringify(data, null, 2)
    case 'csv':
      return convertToCSV(data.accounts)
    case 'txt':
      return convertToTXT(data.accounts)
    case 'xml':
      return convertToXML(data)
    case 'html':
      return convertToHTML(data)
    case 'yaml':
      return convertToYAML(data)
    default:
      return JSON.stringify(data, null, 2)
  }
}

// 转换为CSV
const convertToCSV = (accounts) => {
  const headers = ['名称', '用户名', '网址', '分类', '备注', '收藏', '创建时间', '更新时间']
  if (backupType.value === 'full') {
    headers.splice(2, 0, '密码')
  }
  
  let csv = headers.join(',') + '\n'
  
  accounts.forEach(account => {
    const row = [
      `"${account.name}"`,
      `"${account.username}"`,
      ...(backupType.value === 'full' ? [`"${account.password}"`] : []),
      `"${account.url || ''}"`,
      `"${account.category}"`,
      `"${account.notes || ''}"`,
      `"${account.isFavorite ? '是' : '否'}"`,
      `"${account.createdAt}"`,
      `"${account.updatedAt}"`
    ]
    csv += row.join(',') + '\n'
  })
  
  return csv
}

// 转换为TXT
const convertToTXT = (accounts) => {
  let txt = `密码管理器数据备份\n备份时间: ${new Date().toLocaleString()}\n备份类型: ${backupType.value === 'full' ? '完整备份' : '部分备份'}\n总账号数: ${accounts.length}\n\n`
  
  accounts.forEach((account, index) => {
    txt += `=== 账号 ${index + 1} ===\n`
    txt += `名称: ${account.name}\n`
    txt += `用户名: ${account.username}\n`
    if (backupType.value === 'full') {
      txt += `密码: ${account.password}\n`
    }
    txt += `网址: ${account.url || '无'}\n`
    txt += `分类: ${account.category}\n`
    txt += `备注: ${account.notes || '无'}\n`
    txt += `收藏: ${account.isFavorite ? '是' : '否'}\n`
    txt += `创建时间: ${account.createdAt}\n`
    txt += `更新时间: ${account.updatedAt}\n\n`
  })
  
  return txt
}

// 转换为XML
const convertToXML = (data) => {
  let xml = `<?xml version="1.0" encoding="UTF-8"?>\n`
  xml += `<passwordManager>\n`
  xml += `  <backupInfo>\n`
  xml += `    <date>${data.backupInfo.date}</date>\n`
  xml += `    <type>${data.backupInfo.type}</type>\n`
  xml += `    <version>${data.backupInfo.version}</version>\n`
  xml += `    <totalAccounts>${data.backupInfo.totalAccounts}</totalAccounts>\n`
  xml += `  </backupInfo>\n`
  xml += `  <accounts>\n`
  
  data.accounts.forEach(account => {
    xml += `    <account>\n`
    xml += `      <id>${escapeXml(account.id || '')}</id>\n`
    xml += `      <name>${escapeXml(account.name || '')}</name>\n`
    xml += `      <username>${escapeXml(account.username || '')}</username>\n`
    if (backupType.value === 'full') {
      xml += `      <password>${escapeXml(account.password || '')}</password>\n`
    }
    xml += `      <url>${escapeXml(account.url || '')}</url>\n`
    xml += `      <category>${escapeXml(account.category || '')}</category>\n`
    xml += `      <notes>${escapeXml(account.notes || '')}</notes>\n`
    xml += `      <isFavorite>${account.isFavorite ? 'true' : 'false'}</isFavorite>\n`
    xml += `      <createdAt>${escapeXml(account.createdAt || '')}</createdAt>\n`
    xml += `      <updatedAt>${escapeXml(account.updatedAt || '')}</updatedAt>\n`
    xml += `    </account>\n`
  })
  
  xml += `  </accounts>\n`
  xml += `</passwordManager>`
  
  return xml
}

// 转换为HTML
const convertToHTML = (data) => {
  let html = `<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n`
  html += `  <meta charset="UTF-8">\n`
  html += `  <meta name="viewport" content="width=device-width, initial-scale=1.0">\n`
  html += `  <title>密码管理器数据备份</title>\n`
  html += `  <style>\n`
  html += `    body { font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 20px; background: #f5f5f5; }\n`
  html += `    .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }\n`
  html += `    h1 { color: #333; text-align: center; border-bottom: 2px solid #409EFF; padding-bottom: 10px; }\n`
  html += `    .info { background: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 20px; }\n`
  html += `    table { width: 100%; border-collapse: collapse; margin-top: 20px; }\n`
  html += `    th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }\n`
  html += `    th { background: #409EFF; color: white; font-weight: bold; }\n`
  html += `    tr:nth-child(even) { background: #f9f9f9; }\n`
  html += `    tr:hover { background: #e6f7ff; }\n`
  html += `    .favorite { color: #f56c6c; font-weight: bold; }\n`
  html += `    .password { font-family: monospace; background: #f0f0f0; padding: 2px 5px; border-radius: 3px; }\n`
  html += `    @media print { body { background: white; } .container { box-shadow: none; } }\n`
  html += `  </style>\n</head>\n<body>\n`
  html += `  <div class="container">\n`
  html += `    <h1>🔐 密码管理器数据备份</h1>\n`
  html += `    <div class="info">\n`
  html += `      <p><strong>备份时间：</strong>${data.backupInfo.date}</p>\n`
  html += `      <p><strong>备份类型：</strong>${data.backupInfo.type === 'full' ? '完整备份' : '部分备份'}</p>\n`
  html += `      <p><strong>账号总数：</strong>${data.backupInfo.totalAccounts}</p>\n`
  html += `      <p><strong>版本：</strong>${data.backupInfo.version}</p>\n`
  html += `    </div>\n`
  html += `    <table>\n`
  html += `      <thead>\n        <tr>\n`
  html += `          <th>名称</th><th>用户名</th>`
  if (backupType.value === 'full') {
    html += `<th>密码</th>`
  }
  html += `<th>网址</th><th>分类</th><th>备注</th><th>收藏</th><th>创建时间</th><th>更新时间</th>\n`
  html += `        </tr>\n      </thead>\n      <tbody>\n`
  
  data.accounts.forEach(account => {
    html += `        <tr>\n`
    html += `          <td>${escapeHtml(account.name || '')}</td>\n`
    html += `          <td>${escapeHtml(account.username || '')}</td>\n`
    if (backupType.value === 'full') {
      html += `          <td class="password">${escapeHtml(account.password || '')}</td>\n`
    }
    html += `          <td>${account.url ? `<a href="${escapeHtml(account.url)}" target="_blank">${escapeHtml(account.url)}</a>` : ''}</td>\n`
    html += `          <td>${escapeHtml(account.category || '')}</td>\n`
    html += `          <td>${escapeHtml(account.notes || '')}</td>\n`
    html += `          <td class="${account.isFavorite ? 'favorite' : ''}">${account.isFavorite ? '★' : ''}</td>\n`
    html += `          <td>${account.createdAt ? new Date(account.createdAt).toLocaleString() : ''}</td>\n`
    html += `          <td>${account.updatedAt ? new Date(account.updatedAt).toLocaleString() : ''}</td>\n`
    html += `        </tr>\n`
  })
  
  html += `      </tbody>\n    </table>\n`
  html += `    <div style="margin-top: 30px; text-align: center; color: #666; font-size: 12px;">\n`
  html += `      <p>此文件由密码管理器自动生成 | 请妥善保管此备份文件</p>\n`
  html += `    </div>\n  </div>\n</body>\n</html>`
  
  return html
}

// 转换为YAML
const convertToYAML = (data) => {
  let yaml = `# 密码管理器数据备份\n`
  yaml += `# 备份时间: ${data.backupInfo.date}\n`
  yaml += `# 备份类型: ${data.backupInfo.type === 'full' ? '完整备份' : '部分备份'}\n\n`
  
  yaml += `backupInfo:\n`
  yaml += `  date: "${data.backupInfo.date}"\n`
  yaml += `  type: "${data.backupInfo.type}"\n`
  yaml += `  version: "${data.backupInfo.version}"\n`
  yaml += `  totalAccounts: ${data.backupInfo.totalAccounts}\n\n`
  
  yaml += `accounts:\n`
  data.accounts.forEach((account, index) => {
    yaml += `  - id: "${account.id || ''}"\n`
    yaml += `    name: "${escapeYaml(account.name || '')}"\n`
    yaml += `    username: "${escapeYaml(account.username || '')}"\n`
    if (backupType.value === 'full') {
      yaml += `    password: "${escapeYaml(account.password || '')}"\n`
    }
    yaml += `    url: "${escapeYaml(account.url || '')}"\n`
    yaml += `    category: "${escapeYaml(account.category || '')}"\n`
    yaml += `    notes: "${escapeYaml(account.notes || '')}"\n`
    yaml += `    isFavorite: ${account.isFavorite ? 'true' : 'false'}\n`
    yaml += `    createdAt: "${account.createdAt || ''}"\n`
    yaml += `    updatedAt: "${account.updatedAt || ''}"\n`
    if (index < data.accounts.length - 1) yaml += `\n`
  })
  
  return yaml
}

// 字符转义函数
const escapeXml = (str) => {
  return str.replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
}

const escapeHtml = (str) => {
  return str.replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#x27;')
}

const escapeYaml = (str) => {
  return str.replace(/\\/g, '\\\\')
            .replace(/"/g, '\\"')
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r')
            .replace(/\t/g, '\\t')
}

// 执行备份
const performBackup = async () => {
  try {
    isBackingUp.value = true
    
    // 生成备份数据
    const backupData = generateBackupData()
    let content = convertToFormat(backupData)
    
    // 加密处理
    if (encryptBackup.value && encryptionPassword.value) {
      content = CryptoJS.AES.encrypt(content, encryptionPassword.value).toString()
    }
    
    // 生成文件名
    const timestamp = new Date().toISOString().split('T')[0]
    const typePrefix = backupType.value === 'full' ? 'full' : 'partial'
    const encryptSuffix = encryptBackup.value ? '_encrypted' : ''
    const fileName = `password_backup_${typePrefix}${encryptSuffix}_${timestamp}.${exportFormat.value}`
    
    // 下载文件
    const blob = new Blob([content], { type: getContentType() })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = fileName
    a.click()
    URL.revokeObjectURL(url)
    
    // 记录备份历史
    const backupRecord = {
      name: fileName,
      date: new Date().toLocaleString(),
      type: backupType.value === 'full' ? '完整备份' : '部分备份',
      format: exportFormat.value.toUpperCase(),
      encrypted: encryptBackup.value,
      size: estimatedSize.value,
      accounts: accountsStore.accounts.length
    }
    
    backupHistory.value.unshift(backupRecord)
    if (backupHistory.value.length > 10) {
      backupHistory.value = backupHistory.value.slice(0, 10)
    }
    
    // 保存备份历史到本地存储
    localStorage.setItem('passwordManagerBackupHistory', JSON.stringify(backupHistory.value))
    
    ElMessage.success('备份完成！文件已下载到本地。')
    
  } catch (error) {
    console.error('备份失败:', error)
    ElMessage.error('备份失败，请重试')
  } finally {
    isBackingUp.value = false
  }
}

// 获取内容类型
const getContentType = () => {
  switch (exportFormat.value) {
    case 'json':
      return 'application/json'
    case 'csv':
      return 'text/csv'
    case 'txt':
      return 'text/plain'
    case 'xml':
      return 'application/xml'
    case 'html':
      return 'text/html'
    case 'yaml':
      return 'application/x-yaml'
    default:
      return 'text/plain'
  }
}

// 加载备份历史
const loadBackupHistory = () => {
  try {
    const saved = localStorage.getItem('passwordManagerBackupHistory')
    if (saved) {
      backupHistory.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载备份历史失败:', error)
  }
}

// 下载历史备份（重新生成）
const downloadBackup = (backup) => {
  ElMessage.info('历史备份需要重新生成，当前数据可能已更新')
  performBackup()
}

// 监听visible变化
watch(() => props.visible, (visible) => {
  if (visible) {
    loadBackupHistory()
  }
})
</script>

<style scoped>
.backup-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.backup-container h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.options-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.option-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.option-card.active {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
}

.option-content {
  padding: 8px;
}

.option-info {
  margin-left: 8px;
}

.option-title {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.option-desc {
  font-size: 12px;
  color: #666;
}

.format-options {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.format-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.format-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  padding: 12px;
}

.format-card:hover {
  border-color: #409EFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.format-card.active {
  border-color: #409EFF;
  background: #e6f7ff;
}

.format-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.format-icon {
  font-size: 24px;
  flex-shrink: 0;
}

.format-details {
  flex: 1;
}

.format-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.format-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  line-height: 1.4;
}

.format-features {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.feature-tag {
  background: #e6f7ff;
  color: #1890ff;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
  font-weight: 500;
}

.format-card.active .feature-tag {
  background: #1890ff;
  color: white;
}

.security-options {
  padding: 16px;
  background: #fff5f5;
  border: 1px solid #fed7d7;
  border-radius: 8px;
}

.security-controls {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.encryption-password {
  margin-left: 24px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.password-warning {
  margin-top: 8px;
}

.password-strength {
  display: flex;
  align-items: center;
  gap: 12px;
}

.strength-bar {
  flex: 1;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-fill.weak {
  background: #f56565;
}

.strength-fill.medium {
  background: #ed8936;
}

.strength-fill.strong {
  background: #48bb78;
}

.strength-text {
  font-size: 12px;
  font-weight: 500;
}

.backup-preview {
  padding: 16px;
  background: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
}

.preview-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
}

.stat-label {
  color: #666;
}

.stat-value {
  font-weight: 500;
  color: #333;
}

.backup-history {
  max-height: 200px;
  overflow-y: auto;
}

.no-history {
  text-align: center;
  color: #999;
  padding: 20px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.history-info {
  flex: 1;
}

.history-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.history-details {
  font-size: 12px;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
